package com.kornero.auto.net.parsers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class ParserFactory {

    private static final Logger logger = LoggerFactory.getLogger(ParserFactory.class);

    private static final Map<String, IParser> PARSER_MAP = new HashMap<>();

    public static IParser getParserForUrl(final String url) throws ParserNotFound {
        final URI uri = URI.create(url);
        final String host = uri.getHost();
        try {
            if (!PARSER_MAP.containsKey(host)) {
                final IParser parser = (IParser) Class.forName(getClassName(host)).getConstructor().newInstance();
                PARSER_MAP.put(host, parser);
            }
            return PARSER_MAP.get(host);
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException |
                NoSuchMethodException | InvocationTargetException e) {
            logger.error("getParserForUrl():", e);
        }
        throw new ParserNotFound("getParserForUrl(): Can't find parse for \n\t class = "
                + getClassName(host) + ", \n\t url = " + url);
    }

    public static void closeAllParsers() {
        for (IParser parser : PARSER_MAP.values()) {
            try {
                parser.close();
            } catch (Exception e) {
                logger.error("closeAllParsers(): ", e);
            }
        }
    }

    private static String getClassName(final String host) {
        return "com.kornero.auto.net.parsers." + host + ".Parser";
    }
}
